define(function (require, exports, module) {

    var $ = require("lib/zepto");
    var winDialog = require("lib/winDialog");
    var Player = require("lib/com/player");
    var Util = require("lib/com/util");
    var Dialog = require("./dialog");

    var CLS_ON = 'on';
    var CLS_LUCK = 'luck';
    var CLS_SNOWER = 'snower';

    var TPL_COIN = '<div style="top: {top}; left: {left}; -webkit-animation: fade {t1} {t2}, drop {t1} {t2};">\
				<img src="{url}" style="-webkit-animation: counterclockwiseSpinAndFlip {t5};width:{width}; max-width:{maxHeight}">\
				</div>';

    var gPlayerTop = 0;
    var timer = null;
    var TIMEOUT_DIALOG = 2000;
	
	var _prizelist=[];
	var _mode = APP.diskStyle;
	var _mcmin;
	var _nowPot=-1;
	var _rotation=0; //大转盘的角度
	var _gift_data;
	var pass;
	var _playing=false;//转盘是否正在转动
	var allways;
	/**
     * 大转盘和九宫格
     * @constructor
     */
    function DiceWheel() {
        this.rendered = false;
        // this.mustFollow = APP.mustFollow && !APP.followed;

        this.render();
    }
    DiceWheel.prototype = {
        constructor: DiceWheel,
        // 渲染
        render: function () {
            var _self = this;
            if (!_self.rendered) {
                _self._init();

                _self.rendered = true;
            }
        },
        // 初始化
        _init: function () {
			var _self = this;
            _self._bindUI();
            // 对话框
            _self.dialog = new Dialog("#J_Dialog",_self.pass,CLS_SNOWER);
			
        },
        // 绑定事件
        _bindUI: function () {
            var _self = this;

			$(".btn_start").on("click",function(){
				_self._handleDoLott();
			});
			
            // 中奖纪录
            $('.win-table,.giftBox').delegate("input", "click", function (e) {
                _self._handleWinTable(e.currentTarget);
            });
			
            // 领取任务
            $('.mission').on("click", function (e) {
                _self._handleMission(e.currentTarget);
            });
        },
        // 处理抽奖
        _handleDoLott: function () {
            var _self = this,
                // egg = $(egg),
                dialog = _self.dialog;
				//test = '/?m=shopmobile&c=test&a=startBigWheel'
			if (_self._playing){
				return;
			}
			_self._playing=true;
            // $.getJSON('/?m=shopmobile&c=test&a=startBigWheel',false, function (data) {
				console.log("reday to send data"+_self._mode+"APP.Style"+APP.diskStyle);
				if(APP.chance>0){
					if(APP.diskStyle==2){
						_self.allwaysPlayPan2();
					}else{
						_self.allwaysPlayPan();
					}
				}else{
					_self.alertss('抱歉，<br/>您没有抽奖机会了~<br />请点击锦囊获取机会哦');
					return;
				}
            $.getJSON(APP.urls.win+"&eid="+APP.eid,false, function (data) {
                data = data || {};
				_self._gift_data = data;
				if(APP.chance>0){APP.chance --;}
				$("#J_Times").text(APP.chance);
				var dialog_type = data.success==1?0:(data.success==2?8:null);
				console.log("dialog_type"+dialog_type);
				console.log(JSON.stringify(data));
				clearInterval(_self.allways);
                switch (data.success) {
                    case 1: // 中奖
                    case 2: // 不中奖
					//中奖后应在$('.win-table')增加一个奖品，并绑定动作
						var tmp="";
						tmp+="<tr><td>"+data.actiontime+"</td>";
						tmp+="<td>"+data.giftname+"</td>";
						var params="";
						if(data.cardno){
							params+=" data-cardno=\""+data.cardno+"\"";
							params+=" data-secret=\""+data.secret+"\"";
						}
						params+=" value=\"领取"+data.gtype_name+"\"";
						params+=" data-mygid=\""+data.mygid+"\"";
						params+=" data-gid=\""+data.gid+"\"";
						params+=" data-gtype=\""+data.gtype_code+"\"";
						params+=" data-getway=\""+data.getway+"\"";
						tmp+="<td><input type=\"button\" class=\"js-myg"+data.mygid+"\" "+params +" /></td></tr>";
						$(tmp).delegate("input", "click", function (e) {
							_self._handleWinTable(e.currentTarget);
						});
						$(".win-table").prepend(tmp);
						
						var tmp="";
						tmp+='<div class="codeInfoBox">';
						tmp+='<div class="djqImgBox"><img src="'+data.giftpic+'_200x200.jpg"/></div>';
						tmp+='<div class="isEmptyAward ellipsis">'+data.giftname+'</div>';
						//<!--div class="codeperiod" style="margin: 0.25rem 0.6rem;"><span>兑奖期限</span>：2016.07.20 至 2016.07.27</div-->
						//tmp+='<div class="goDetailIcon">'+medal[m].get_time+'</div>';
						tmp+='<div class="awardWrap"></div>';
						
						var params="";
						if(data.cardno){
							params+=" data-cardno=\""+data.cardno+"\"";
							params+=" data-secret=\""+data.secret+"\"";
						}
						params+=" value=\"领取"+data.gtype_name+"\"";
						params+=" data-mygid=\""+data.mygid+"\"";
						params+=" data-gid=\""+data.gid+"\"";
						params+=" data-gtype=\""+data.gtype_code+"\"";
						params+=" data-getway=\""+data.getway+"\"";
						
						tmp+="<div class=\"buttons\"><input type=\"button\" class=\"js-myg"+data.mygid+"\" "+params +" /></div>";
						tmp+='</div>';
						$("#giftAward").prepend(tmp);
						if(!APP.prizeList){// 外观没有配置奖品
							_self.dialog.renderUI(Dialog.TYPE.take, _self._gift_data);
							return;
						}
						
						var priz=new Array();
						for(var i=0;i<APP.prizeList.length;i++){
							if(parseInt(APP.prizeList[i].prizeId)==parseInt(data.gid)){
								priz.push(APP.prizeList[i]);
							}
						}
						var l = parseInt(Math.random()*priz.length);
						var pri = priz[l];//相同的奖品位置随机抽取
						console.log(JSON.stringify(pri)+"||"+l);
						if(!pri.prizePostition){//如果位置出错，直接弹出对话框
							_self.showOverPrize(pri,dialog_type);
							return;
						}
						if(APP.diskStyle==2){
							console.log(parseInt(pri.prizePostition)-1);
							_self.playPan2(parseInt(pri.prizePostition)-1,pri, dialog_type); //最后一个参数，0=中奖，8=不中奖
						}else{
							//var _wins=[337.5,292.5,247.5,202.5,157.5,112.5,67.5,22.5]; //转盘逆时针位置
							var _wins=[22.5,67.5,112.5,157.5,202.5,247.5,292.5,337.5]; //转盘顺时针位置
							_self.playPan(_wins[parseInt(pri.prizePostition)-1],pri, dialog_type);
						}
                        // _self.pass.play(true);
                        // egg.toggleClass(CLS_LUCK);
                        break;
                    // case 2: // 未中奖
							// _self.alertss('太可惜了，<br/>差一点就中奖了~'); //使用当前外观的对话框
                        // break;
                    case 3: // 天次数用完
                            dialog.renderUI(Dialog.TYPE.noDayTimes, data);
                        break;
                    case 4: // 总次数用完
                            dialog.renderUI(Dialog.TYPE.noAllTimes, data);
                        break;
                    default: // 异常提示
                            dialog.renderUI(Dialog.TYPE.noDayTimes, {title: data.error});
                }
            });
        },
        // 重置参与次数
        _resetCount: function (num) {
            if (num || num == 0) {
                $('#J_Times').text((+num)||0);
            }
        },
        // 处理中奖记录
        _handleWinTable: function (btn) {
            var _self = this,
                dialog = _self.dialog;

            var btn = $(btn),
                getway = btn.attr("data-getway"),
                gtype = btn.attr("data-gtype"),
                mygid = btn.attr("data-mygid"),
                gid = btn.attr("data-gid"),
                cardno = btn.attr("data-cardno"),
                secret = btn.attr("data-secret"),
                url;
			var options = {"getway": getway, "mygid": mygid, "gid": gid,"cardno":cardno,"secret":secret};
				dialog.renderUiSwitch(options);
        },
		
		//处理领取任务
		_handleMission:function(btn){
            var _self = this,
                dialog = _self.dialog;

            var btn = $(btn),
				mis = btn.attr("data-mis"),
				options = {"mis":mis,"eid":APP.eid};
				switch(mis){
					case "everyday" :
						$.getJSON(APP.urls.mission,options,function(json){
							alert(json.msg);
						});
					break;
					case "sign" :
						var day = new Date();
					    options.curdate = day.getFullYear()+"-"+(day.getMonth()+1)+"-"+day.getDate();
						$.getJSON(APP.urls.mission,options,function(json){
							if(json.hasError){
								alert("抱歉，不能进行签到！"+json.msg);
								return;
							}
							$(".poupFadIn").hide();
							options.signList = json.setting;
							dialog.renderUI(Dialog.TYPE.signDays, options);
						});
					break;
					case "order" :
						$(".poupFadIn").hide();
						dialog.renderUI(Dialog.TYPE.orderChance, options);
					break;
					case "jifen" :
						$.getJSON(APP.urls.mission,options,function(json){
							if(json.setting.onoff_jfdh==1){
								$(".poupFadIn").hide();
								options.setting = json.setting;
								dialog.renderUI(Dialog.TYPE.jifenChance, options);
							}else{
								alert("抱歉！积分兑换功能已关闭。");
							}
						});
					break;
					case "cartadd" :
						$.getJSON(APP.urls.mission,options,function(json){
							$(".poupFadIn").hide();
							dialog.renderUI(Dialog.TYPE.addCartChance, {"cart_items":json.setting,"cart_cfg":json.cart_cfg,"eid":APP.eid});
						});
					break;
				}
		},
        // 飘银元
        _fallCoin: function () {
            var snowsDom = $('.' + CLS_SNOWER),
                img = APP.imgs.coin,
                num = Math.random() * 8 + 7 | 0,
                snows = Array(num).join(",").split(","),
                snowsHTML = "";

            if (!snowsDom.length) {
                snowsHTML = Util.template(TPL_COIN, snows, function () {
                    return {
                        top: "-30px",
                        left: Math.random() * 100 + "%",
                        t1: Math.random() * (8 - 3) + 2 + "s",
                        t2: Math.random() * 2 + "s",
                        t5: Math.random() * (8 - 3) + 2 + "s",
                        url: img,
                        width: Math.round(Math.random() * (38 - 10) + 10) + "px",
                        maxHeight: "43px"
                    };
                });
                snowsDom = $('<div class="' + CLS_SNOWER + '">' + snowsHTML + '</div>');
                $(document.body).append(snowsDom);
            } else {
                snowsDom.show();
            }
        },
        // 创建指定样式名的DOM
        createDomByClass: function (sClass) {
            var jDom = $('.' + sClass);
            if (!jDom.length) {
                jDom = $('<div class="' + sClass + '"></div>');
                $(document.body).append(jDom);
            }

            return jDom;
        },
		/***转盘***/
		
		allwaysPlayPan:function(){
			var _self=this;
			var t=0;
			_self.allways = setInterval(function (){
				// _self._mcmin.rotation+=3;
				_rotation += 10;
				$(".wheel").css({
					'transition-timing-function':'linear',
					'-webkit-transition': 'all 0.3s',
					'transition': 'all 0.3s',
					'-webkit-transform': 'rotate(' + (_rotation) + 'deg)',
					'transform': 'rotate(' + (_rotation) + 'deg)'
				});
				if(t>30){
					clearInterval(_self.allways);
					alert("抱歉，请求超时，请检查您的网络");
				}
				t++;
			},200);
		}, //在返回数据之前总是旋转
		playPan: function (c,d,t){
				var _self=this;
				$(".wheel").css({
					'-webkit-transition': 'all 5s',
					'transition': 'all 5s',
					'-webkit-transform': 'rotate(' + (c+(3600)) + 'deg)',
					'transform': 'rotate(' + (c+(3600)) + 'deg)'
				});
				setTimeout(function(){
					_self.showOverPrize(d,t);
					_self._playing=false;
				},5100);
		},
			/***转盘***/
		allwaysPlayPan2:function(){ //在返回数据之前总是旋转
			var _self=this;
			var t = 0;
			_self.allways = setInterval(function (){
				// console.log(".gift_cover"+_nowPot);
				$(".gift_cover"+_nowPot).hide();
				_nowPot++;
				$(".gift_cover"+_nowPot).show();
				// for(var i=0;i<8;i++){
					// if(_nowPot!=i){
						// $(".gift_cover"+_nowPot).hide();
					// }
				// }
				if(_nowPot>7){
					_nowPot%=8;
				}
				if(t>200){
					$(".gift_cover"+_nowPot).show();
					clearInterval(_self.allways);
					alert("抱歉，请求超时，请检查您的网络");
				}
				t++;
			},60);
			
		},
		playPan2:function (c,d,t){
				var _self = this;
				var _downstart=c;
				var _maxspeed=3;
				for(var i=_maxspeed;i<25;i+=2){
					_downstart-=i;
					if(_downstart<0) _downstart+=8;
				}
				;
				for(var i=0;i<8;i++){
					$(".gift_cover"+_nowPot).hide();
				}
				$(".btn_nostart").show();
				var _speed=8;
				var _quan=5;
				var _ss=7;
				
				var fps = setInterval(function(){
					_ss++;
					if(_ss==_speed){
						if(_quan==-1){
							_speed+=2;
						}else if(_quan==0&&_downstart==_nowPot){
							_quan=-1;
						}
						if(_nowPot!=-1){
							$(".gift_cover"+_nowPot).hide();
							// _self._mcmin['t_'+_nowPot].gotoAndStop(0);
						}
						_nowPot++;
						if(_nowPot>7){
							_nowPot%=8;
							if(_speed==_maxspeed){
								_quan--;
							}
						}
						$(".gift_cover"+_nowPot).show();
						// _self._mcmin['t_'+_nowPot].gotoAndStop(1);
						if(_speed>_maxspeed&&_quan>0){
							_speed-=2;
						}else if(_speed<=_maxspeed){
							_speed=_maxspeed;
						}
						_ss=0;
						if(_speed>24&&c==_nowPot){
							// _self._mcmin.bg.gotoAndStop(0);
							clearInterval(fps);
							setTimeout(function(){
								// _self.dialog.renderUI(Dialog.TYPE.take, d);
								_self.showOverPrize(d,t);
								_self._playing=false;
								$(".btn_nostart").hide();
							},(_nowPot*30)+300);
						}
					}
				},30);
			},
			    /***显示结果***/
			showOverPrize:function (d,t){
				var _self = this;
				if(t==8){
					_self.alertss('太可惜了，<br/>差一点就中奖了~');
				}else{
					_self.showTCSp($('.winner'));
					// $('.winner .btn_close').off('click');
					$('.winner .says').html(d.prizeName);
					$('.winner .prizeimg img').attr('src', d.prizePic);
					// _self._fallCoin();
				}

			},
			alertss:function (str,fun){
				var _self = this;
				var mc;
				if($('.alertss').length==0){
					var dd='<div class="tan alertss" style="z-index:9999"><div class="cons"><img src="/assets/shopmobile/bigwheel/images/btn_alert_bg.png" class="bg">'+
						'<div class="con"><p class="says">sss</p><a href="javascript:;" class="btn_close">知道了</a></div></div></div>';
					mc=$(dd);
					$('body').append(mc);
				}else{
					mc=$('.alertss');
				}
				mc.find('.says').html(str);
				_self.showTCSp(mc,function(){
					if(fun!=undefined) fun();
				});

			},
			showTCSp:function (mc,fun) {
				mc.show();
				var _self=this;
				var c = mc.find('.cons');
				var h = c.height();
				var hh = $(window).height();
				var ccsd = (hh - h) / 2;
				if (ccsd < 0) ccsd = 0;
				c.css({'top': ccsd});
				if (h > hh) hh = h;
				$('.daddy').css({'height': hh, 'overflow': 'hidden'});

				mc.find('.btn_close').on('click', function () {
					console.log("getgift");
					if(typeof(_self._gift_data)!="undefined" && _self._gift_data.success==1){
					_self.dialog.renderUI(Dialog.TYPE.take, _self._gift_data);
					}
					mc.find('.btn_close').off('click');
					$('.daddy').css({'height':'auto','overflow':'inherit'});
					mc.hide();
					if (fun != undefined) fun()
				});
			}
    };

    module.exports = DiceWheel;
});
